<template>
  <view class="loan-form-container">
    <view class="page-header">
      <view class="header-left" @click="goBack">
        <u-icon name="arrow-left" size="20" color="#333"></u-icon>
        <text>返回</text>
      </view>
      <view class="header-title">创建借条</view>
      <view class="header-right"></view>
    </view>
    
    <!-- 表单区域 -->
    <view class="form-section">
      <!-- 借款方/出借方 -->
      <view class="form-item">
        <view class="form-label">{{ isLender ? '借款方' : '出借方' }}</view>
        <view class="form-input-wrapper">
          <input class="form-input" :placeholder="`请填写${isLender ? '借款方' : '出借方'}`" v-model="formData.counterparty" disabled />
          <view class="arrow-icon">
            <u-icon name="arrow-right" color="#ccc" size="24"></u-icon>
          </view>
        </view>
      </view>
      
      <!-- 欠款金额 -->
      <view class="form-item">
        <view class="form-label">欠款金额</view>
        <view class="form-input-wrapper">
          <input class="form-input" placeholder="请填写欠款金额" type="digit" v-model="formData.amount" />
          <view class="unit">元</view>
        </view>
      </view>
      
      <!-- 还款方式 -->
      <view class="form-item">
        <view class="form-label">还款方式</view>
        <view class="form-input-wrapper">
          <input class="form-input" placeholder="一次性还本付息" v-model="formData.repaymentMethod" disabled />
          <view class="arrow-icon">
            <u-icon name="arrow-right" color="#ccc" size="24"></u-icon>
          </view>
        </view>
      </view>
      
      <!-- 年化利率 -->
      <view class="form-item">
        <view class="form-label">年化利率</view>
        <view class="form-input-wrapper">
          <input class="form-input" placeholder="0" type="digit" v-model="formData.interestRate" />
          <view class="unit">%</view>
        </view>
      </view>
      
      <!-- 起始日期 -->
      <view class="form-item" @click="showStartCalendar = true">
        <view class="form-label">起始日期</view>
        <view class="form-input-wrapper">
          <text class="form-input">{{ formData.startDate }}</text>
          <view class="arrow-icon">
            <u-icon name="calendar" color="#ccc" size="24"></u-icon>
          </view>
        </view>
      </view>
      
      <!-- 还款日期 -->
      <view class="form-item" @click="showEndCalendar = true">
        <view class="form-label">还款日期</view>
        <view class="form-input-wrapper">
          <text class="form-input">{{ formData.endDate }}</text>
          <view class="arrow-icon">
            <u-icon name="calendar" color="#ccc" size="24"></u-icon>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 欠条原因 -->
    <view class="reason-section">
      <view class="section-title">欠条原因</view>
      
      <view class="reason-options">
        <view 
          v-for="(reason, index) in reasons" 
          :key="index" 
          class="reason-tag" 
          :class="{ active: formData.reason === reason }"
          @click="selectReason(reason.id)"
        >
          {{ reason.name }}
        </view>
      </view>
      
      <view class="reason-input">
        <textarea 
          placeholder="点击输入更详细的欠条原因" 
          v-model="formData.detailedReason"
          class="detailed-reason"
        ></textarea>
      </view>
    </view>
    
    <!-- 下一步按钮 -->
    <view class="next-btn" @click="nextStep">下一步</view>
    
    <!-- 日历组件 - 起始日期 -->
    <u-calendar
      :show="showStartCalendar"
      :mode="calendarMode"
      :min-date="minDate"
      :monthNum="12"
      :defaultDate="startDefaultDate"
      color="#1989fa"
      @confirm="confirmStartDate"
      @close="showStartCalendar = false"
    ></u-calendar>
    
    <!-- 日历组件 - 还款日期 -->
    <u-calendar
      :show="showEndCalendar"
      :mode="calendarMode"
      :min-date="startDate"
      :monthNum="12"
      :defaultDate="endDefaultDate"
      color="#1989fa"
      @confirm="confirmEndDate"
      @close="showEndCalendar = false"
    ></u-calendar>
  </view>
</template>

<script>
import { getLoanReason } from '@/api/user'
export default {
  data() {
    const currentDate = new Date();
    const currentTimestamp = currentDate.getTime();
    
    // 计算最大日期（10年后）
    const maxDate = new Date();
    maxDate.setFullYear(maxDate.getFullYear() + 10);
    
    return {
      isLender: false,
      currentDate: this.formatDate(currentDate),
      reasons: [],
      formData: {
        counterparty: '',
        amount: '',
        repaymentMethod: '一次性还本付息',
        interestRate: '0',
        startDate: this.formatDate(currentDate),
        endDate: this.formatDate(new Date(currentDate.getTime() + 30 * 24 * 60 * 60 * 1000)), // 默认30天后
        reason: '',
        detailedReason: ''
      },
      // 日历组件相关
      calendarMode: 'single',
      showStartCalendar: false,
      showEndCalendar: false,
      startDateTimestamp: currentTimestamp,
      endDateTimestamp: currentTimestamp + 30 * 24 * 60 * 60 * 1000, // 默认30天后
      minDate: this.getDateString(new Date(currentTimestamp - 7 * 24 * 60 * 60 * 1000)), // 允许选择7天前
      maxDate: this.getDateString(maxDate),
      maxEndDate: this.getDateString(maxDate),
      startDefaultDate: this.getDateString(currentDate),
      endDefaultDate: this.getDateString(new Date(currentTimestamp + 30 * 24 * 60 * 60 * 1000)),
      startDate: this.getDateString(currentDate)
    }
  },
  onLoad() {
    // 获取用户角色
    const role = uni.getStorageSync('userRole');
    this.isLender = role === 'lender';
    
    // 设置默认对方
    if (this.isLender) {
      this.formData.counterparty = '请填写借款方';
    } else {
      this.formData.counterparty = '请填写出借方';
    }
    getLoanReason().then(res => {
      console.debug(res)
      this.reasons = res.data.data
    })
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}/${month}/${day}`;
    },
    
    getDateString(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    
    selectReason(reason) {
      this.formData.reason = reason;
    },
    
    confirmStartDate(e) {
      const timestamp = new Date(e.year, e.month - 1, e.day).getTime();
      this.startDateTimestamp = timestamp;
      this.formData.startDate = this.formatDate(new Date(timestamp));
      this.showStartCalendar = false;
      
      // 更新最小结束日期
      const selectedDate = new Date(timestamp);
      this.startDate = this.getDateString(selectedDate);
      this.startDefaultDate = this.getDateString(selectedDate);
      
      // 如果结束日期早于开始日期，则更新结束日期
      if (this.endDateTimestamp < timestamp) {
        // 默认设置为开始日期后30天
        const newEndDate = new Date(timestamp);
        newEndDate.setDate(newEndDate.getDate() + 30);
        this.endDateTimestamp = newEndDate.getTime();
        this.formData.endDate = this.formatDate(newEndDate);
        this.endDefaultDate = this.getDateString(newEndDate);
      }
    },
    
    confirmEndDate(e) {
      const timestamp = new Date(e.year, e.month - 1, e.day).getTime();
      this.endDateTimestamp = timestamp;
      this.formData.endDate = this.formatDate(new Date(timestamp));
      this.endDefaultDate = this.getDateString(new Date(timestamp));
      this.showEndCalendar = false;
    },
    
    nextStep() {
      // 表单验证
      if (!this.formData.counterparty || this.formData.counterparty.includes('请填写')) {
        return uni.showToast({
          title: `请选择${this.isLender ? '借款方' : '出借方'}`,
          icon: 'none'
        });
      }
      
      if (!this.formData.amount) {
        return uni.showToast({
          title: '请填写欠款金额',
          icon: 'none'
        });
      }
      
      if (!this.formData.reason) {
        return uni.showToast({
          title: '请选择欠条原因',
          icon: 'none'
        });
      }
      
      // 保存表单数据
      uni.setStorageSync('loanFormData', this.formData);
      
      // 跳转到确认页面
      uni.navigateTo({
        url: '/pages/loan/confirm'
      });
    }
  }
}
</script>

<style lang="scss">
.loan-form-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-bottom: 40rpx;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 90rpx;
  background-color: #fff;
  padding: 0 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-left text {
  margin-left: 10rpx;
  font-size: 28rpx;
  color: #333;
}

.header-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.header-right {
  width: 60rpx;
}

.form-section {
  background-color: #fff;
  border-radius: 12rpx;
  margin: 20rpx;
  padding: 0 30rpx;
}

.form-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1px solid #f0f0f0;
}

.form-item:last-child {
  border-bottom: none;
}

.form-label {
  font-size: 30rpx;
  color: #333;
  width: 160rpx;
}

.form-input-wrapper {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.form-input {
  text-align: right;
  font-size: 30rpx;
  color: #333;
  flex: 1;
}

.unit {
  color: #999;
  font-size: 30rpx;
  margin-left: 10rpx;
}

.arrow-icon {
  margin-left: 10rpx;
}

.reason-section {
  background-color: #fff;
  border-radius: 12rpx;
  margin: 20rpx;
  padding: 30rpx;
}

.section-title {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 30rpx;
}

.reason-options {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.reason-tag {
  padding: 15rpx 30rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #333;
}

.reason-tag.active {
  background-color: #1989fa;
  color: #fff;
}

.reason-input {
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 20rpx;
  min-height: 150rpx;
}

.detailed-reason {
  width: 100%;
  height: 150rpx;
  font-size: 28rpx;
  color: #333;
}

.next-btn {
  height: 90rpx;
  background-color: #1989fa;
  color: #fff;
  font-size: 32rpx;
  border-radius: 45rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 40rpx 20rpx;
}
</style> 